package com.sync.syncmasterdata.customer.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sync.syncmasterdata.configuration.ConfInfo;
import com.sync.syncmasterdata.customer.pojo.*;
import com.sync.syncmasterdata.customer.pojo.bip.CustomerForBip;
import com.sync.syncmasterdata.customer.service.convert.*;
import com.sync.syncmasterdata.customer.service.impl.BipCustomerServiceImpl;
import com.sync.syncmasterdata.dingrobot.service.DingAPIService;
import com.sync.syncmasterdata.dingrobot.service.DingRobotService;
import com.sync.syncmasterdata.customer.service.impl.SyncServiceImpl;
import com.sync.syncmasterdata.util.DingMessageUtil;
import com.sync.syncmasterdata.util.NormalUtil;
import com.sync.syncmasterdata.vendor.controller.VendorSyncController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.sync.syncmasterdata.util.NormalUtil.stringToMap;

/**
 * 客户同步 controller 层
 */

@RestController
@RequestMapping("/customerSync")
@Slf4j
public class CusSyncController {

    //钉钉服务
    @Autowired
    private DingMessageUtil dingMessageUtil;

//    private DingRobotService dingRobotService;

    @Autowired
    private VendorSyncController vendorSyncController;

    @Autowired
    private SyncServiceImpl syncService;

    @Autowired
    private BipCustomerServiceImpl bipCustomerService;

    @Autowired
    private CrmToBip crmToBip;

    @Autowired
    private CrmToU8 crmToU8;

    @Autowired
    private CrmToOA crmToOA;

    @Autowired
    private OAToU8 oaToU8;

    @Autowired
    private OAToBip oaToBip;

    @Autowired
    private CrmToGsp crmToGsp;

    @Autowired
    private static ConfInfo confInfo;

    //测试=1连接；正式连接=2
    private static String ds_s = "2";


    /**
     * 从 crm 下发 客户信息 到 业务中台
     * add=新增 edit=修改
     */
    @PostMapping("/crmPush")
    @ResponseBody
    public String crmCustomerPush(@RequestParam(value = "guid") String guid, @RequestParam(value = "prod") String prod) {
        log.info("入参展示----guid-{}-------prod-{}", guid, prod);
        //钉钉消息map
        Map<String, String> msgMap = new HashMap<>();
        //钉钉 user list
//        List<String> msgUsers=this.dingAPIService.convertPhoneToUseridList(Arrays.asList("15267167276"));

        if ("".equals(guid)) {
            return "guid异常";
        }

        if ("add".equals(prod)) {
            //回调crm获取客户信息
            CrmCustomer crmCustomer = syncService.getCrmAccount(guid);

            log.info("源头CRM-需要新增的CRM客户对象为：{}", crmCustomer.toString());
            //crm客户对象 转 U8客户对象 --> 推送u8客户新增接口
            U8Customer u8Customer = crmToU8.convertFun(crmCustomer, prod);
            String u8id = this.syncService.pushU8AccountForAdd(u8Customer, ds_s);
            log.info("源头CRM-新增U8ID：" + u8id);
            crmCustomer.setNew_erp_num(u8id);
            u8Customer.setCode(u8id);
            if (u8id == null) {
                //钉钉报警
                dingMessageUtil.pushMessage(null, "prod=add; U8新增客户出错，请查看日志");
                return "prod=add; U8新增客户出错，请查看日志";
            }
            //2025-06改造增加bip的推送
            handleBipCustomerFromCrm(crmCustomer);

            //crm客户对象 转 oa客户对象-->推送oa新增接口(验重客户名称在oa接口服务层)
            OACustomer oaCustomer = crmToOA.convertFun(crmCustomer, "add");
            String oaid = this.syncService.pushOaAccountForAdd(oaCustomer);
            log.info("新增OAID：{}", oaid);
            crmCustomer.setNew_oa_id(oaid);
            //crm客户对象 转 wms客户对象-->推送wms接口新增 (客户信息首次新增，不用同步wms，更新时需要,状态为已发货的才同步到wms)

            //crm客户对象 转 每刻客户对象-->推送每刻新增接口 不推送账号等信息(20220816取消) 改为钉钉提醒手动添加 (20231222更新为 crm 新增后会推送到每刻的自定义档案中)
//            pushMaycurPartner(u8Customer, new HashMap<>());
            pushCustomReferenceToMaycur(u8Customer);
            dingMessageUtil.pushMessage(null, "U8添加了客户" + u8Customer.getAbbrname() + ";-ID为:" + u8id + ",请根据需求,可以手动增加到每刻的往来客商档案!");
            //业务中台处理 推送业务中台客户应用接口，接收所有已经推送系统的客户id

            //更新crm客户档案 中 oa,erp id字段 (接口更新)
            Map<String, Object> map = new HashMap<>();
            map.put("new_oa_id", crmCustomer.getNew_oa_id());
            map.put("new_erp_num", crmCustomer.getNew_erp_num());
            CrmCustomer customer = this.syncService.updateCrmAccount(map, crmCustomer.getAccountid());
            //在安迈BPM中创建客户信息(体外公司同步用)
            String retAmU8 = this.syncService.pushU8AccountForAdd(u8Customer, "3");
            //美博特BPM中创建客户信息(体外公司同步用)
            String retMeiBTU8 = this.syncService.pushU8AccountForAdd(u8Customer, "5");
            log.info("打印安迈的U8推送结果======>>>>" + retAmU8);
            if (customer != null) {
                dingMessageUtil.pushMessage(null, "CRM 新增客户推送完成");
                return "CRM 新增客户推送完成";
            } else {
                //钉钉报警
                dingMessageUtil.pushMessage(null, "CRM (已经通过sql搜索ERP客户) 新增客户推送异常，请检查（crm客户档案guid=" + customer.getAccountid() + "）");
                return "CRM (已经通过sql搜索ERP客户) 新增客户推送异常，请检查";
            }
        } else if ("edit".equals(prod)) {   //接口操作为 edit（编辑）
            Map<String, Object> mapCrmUp = new HashMap<>();
            //回调crm获取客户对象
            CrmCustomer crmCustomer = syncService.getCrmAccount(guid);
            if (Objects.isNull(crmCustomer)) {
                return "prod=edit时 guid获取到的为空，edit过程终止";
            }
            String cusName = crmCustomer.getName();
            String u8id = "";
            String oaid = "";
            String wmsid = "";
            //通过u8id字段 验证是否能更新
            if (StringUtils.isBlank(crmCustomer.getNew_erp_num())) {
                //新增 erp 操作
                U8Customer u8Customer = crmToU8.convertFun(crmCustomer, "add");
                u8id = this.syncService.pushU8AccountForAdd(u8Customer, ds_s);
                mapCrmUp.put("new_erp_num", u8id);
            } else {
                U8Customer u8Customer = crmToU8.convertFun(crmCustomer, "edit");
                //更新 erp 操作(博圣体系)
                this.syncService.pushU8AccountForEdit(u8Customer, ds_s);
                //更新 bip 客户对象
                bipCustomerService.handleUpdateCustomerData(crmCustomer);

                //更新 安迈ERP 体系
                this.syncService.pushU8AccountForEdit(u8Customer, "3");
                //更新 美博特erp
                this.syncService.pushU8AccountForEdit(u8Customer, "5");
            }
            //oaid字段，验证是否更新
            if (StringUtils.isBlank(crmCustomer.getNew_oa_id())) {
                //新增 oa 操作
                OACustomer oaCustomer = crmToOA.convertFun(crmCustomer, "add");
                oaid = this.syncService.pushOaAccountForAdd(oaCustomer);
                mapCrmUp.put("new_oa_id", oaid);
            } else {
                //更新 oa 操作
                OACustomer oaCustomer = crmToOA.convertFun(crmCustomer, "edit");
                this.syncService.updateOaAccount(oaCustomer, oaCustomer.getId());
            }

            //每刻自定义档案更新(客户),若不存在，会自动新增，无须调用pushCustomReference方法
            editCustomReference(crmToU8.convertFun(crmCustomer, "edit"));

            //WMS客户的更新处理 new_type=1 或者4 的类型 且必须为已发货的
            if (crmCustomer.getNew_account() == 3 && (crmCustomer.getNew_type() == 1 || crmCustomer.getNew_type() == 4)) {
                //新增记录(重复会报文不同) 斐创wms的 作废
//                WmsCustomer wmsCustomer = this.crmToWms.convertFun(crmCustomer);
//                String wmsguid = syncService.pushWmsAccountForAdd(wmsCustomer);
//                log.info("WMS系统(1.发货的才创建wms记录 2.搜索是否存在)新增guid：{}", wmsguid);
                GspCustomer gspCustomer = crmToGsp.convertFun(crmCustomer);
                String ret = syncService.pushGspAccountForAdd(gspCustomer);
                try {
                    JSONObject retJson = new JSONObject(ret);
                    JSONObject resultJson = retJson.getJSONObject("fluxredt");
                    if (resultJson.getString("returnFlag").equals("0")) {
                        dingMessageUtil.pushMessage(null, "CRM修改触发 GSP系统新增客户信息(1.需要发货创建GSP记录)：" + ret);
                    }
                } catch (JSONException e) {
                    dingMessageUtil.pushMessage(null, "CRM修改触发 GSP系统新增客户信息异常，请检查(1.需要发货创建GSP记录)：");
                }
            }

            //更新crm客户档案中，u8id || oaid的判断
            if (mapCrmUp.size() > 0) {
                this.syncService.updateCrmAccount(mapCrmUp, crmCustomer.getAccountid());
                log.info("源头CRM-更新ERP客户档案，U8ID||OAID为空，新增、更新完成：{}", crmCustomer.getAccountid());
                dingMessageUtil.pushMessage(null, "源头CRM-更新ERP客户档案，U8ID||OAID为空，新增、更新完成：" + crmCustomer.getAccountid());
                return "源头CRM-更新ERP客户档案，U8ID||OAID为空，新增、更新完成：" + crmCustomer.getAccountid();
            }
            log.info("源头CRM-更新ERP客户档案，更新完成：{}", crmCustomer.getAccountid());
            return "源头CRM-更新ERP客户档案，更新完成" + crmCustomer.getAccountid();
        } else {
            return "prod 参数异常";
        }
    }

    /**
     * oa 新建客户（表单建模） 推送u8  头部增加prod 处理字符 计划不用
     *
     * @param oaCustomer
     * @return
     */
    @PostMapping("/oaPush")
    @Deprecated
    @ResponseBody
    public synchronized String oaCustomerPush(@RequestBody OACustomer oaCustomer, @RequestHeader String prod) {
        Map<String, String> msgMap = new HashMap<>();

        /**
         * 如果类型为供应商或者行政采购
         * 如果推送为供应商类型，取消推送；
         * 需要推送每刻
         */
        if (oaCustomer.getKehulb() == 1 || oaCustomer.getKehulb() == 10) {
            this.vendorSyncController.oaVendorPushForAdd(oaCustomer);
//            Map<String, String> tmpM = new HashMap<>();
//            tmpM.put("content", "OA推送新增或者修改的信息为 '供应商'类型，执行供应商同步操作");
//            this.dingRobotService.robotSendSampleMsg(tmpM, msgUsers);
            return "OA推送新增或者修改的信息为 '供应商'类型，执行供应商同步操作";
        }


        //否则为客户新增或修改的事物处理
        if (prod.equals("add")) {
            //oa客户对象 转 u8客户对象
            U8Customer u8Customer = this.oaToU8.convertFun(oaCustomer, prod);

            //推送u8客户新增接口（创建客户）
            String u8id = this.syncService.pushU8AccountForAdd(u8Customer, ds_s);
            //推送体外公司-安迈
            String u8AnMai = this.syncService.pushU8AccountForEdit(u8Customer, "3");
            String u8Meibt = this.syncService.pushU8AccountForEdit(u8Customer, "5");
            log.info("源头OA-新增U8ID：" + u8id);
            if (u8id == null) {
                //钉钉报警
                dingMessageUtil.pushMessage(null, "新增客户源头OA，U8OPENAPI返回NULL");
                return "源头OA-更新结果：新增客户源头OA，U8OPENAPI返回NULL";
            }
            oaCustomer.setU8kehubm(u8id);
            u8Customer.setCode(u8id);
            //更新oa对象 U8ID
            String returnStr = this.syncService.updateOaAccount(oaCustomer, oaCustomer.getId());
            //推送BIP系统 todo:12月底前使用
            handleBipCustomerFromOA(oaCustomer, "add");

            //推送每刻 往来客户信息
            Map<String, String> accMap = new HashMap<>();
            if (!NormalUtil.null2String(oaCustomer.getLianhangh()).equals("") || !NormalUtil.null2String(oaCustomer.getZhanghao()).equals("")) {
                accMap.put("accountType", "BANK");
                accMap.put("accountName", oaCustomer.getKehumc());
                accMap.put("accountNumber", NormalUtil.trimString(oaCustomer.getZhanghao()));
                accMap.put("bankBranchNo", oaCustomer.getLianhangh());
            }
            //取消推送每刻往来
//            pushMaycurPartner(u8Customer, accMap);
            //推送到每刻自定义档案中
            pushCustomReferenceToMaycur(u8Customer);
            log.info("源头OA-更新结果：{}", returnStr);
            return "源头OA-更新结果：" + returnStr;
        } else if (prod.equals("edit")) {
            //oa数据源 接口操作为 edit
            //如果 OA 表单中 u8kehubm="" 检测是否重复（如果没有，推送U8客户新增接口）
            if (StringUtils.isBlank(oaCustomer.getU8kehubm())) {
                //检查erp中是否存在此客户
                String _kh = this.syncService.checkErpCustomer(oaCustomer.getKehumc());
                if ("".equals(_kh)) {
                    //erp不存在客户
                    //oa客户对象 转 erp客户对象，并推送erp客户新增接口
                    U8Customer u8Customer = this.oaToU8.convertFun(oaCustomer, prod);
                    String u8id = this.syncService.pushU8AccountForAdd(u8Customer, ds_s);
                    log.info("源头OA-新增U8ID：" + u8id);
                    oaCustomer.setU8kehubm(u8id);
                    //oa更新时，erp客户新增完毕
                    String returnStr = this.syncService.updateOaAccount(oaCustomer, oaCustomer.getId());
                    u8Customer.setCode(u8id);
                    String u8idanmai = this.syncService.pushU8AccountForAdd(u8Customer, "3");
                    log.info("源头OA-更新(oa更新时，erp客户并不存在，erp新增)博圣结果：{}", returnStr);
                    log.info("源头OA-新增U8ID-安迈结果：" + u8idanmai);
                    return "源头OA-更新结果：{}" + returnStr;
                } else {
                    //erp存在，但是oa可能没有维护字段,进行维护
                    oaCustomer.setU8kehubm(_kh);
                    String returnStr = this.syncService.updateOaAccount(oaCustomer, oaCustomer.getId());
                    log.info("源头OA-更新(erp存在，但是oa可能没有维护字段,进行维护)结果：{}", returnStr);
                    return "源头OA-更新结果：{}" + returnStr;
                }
            } else {
                //正常更新
                U8Customer u8Customer = this.oaToU8.convertFun(oaCustomer, prod);
                String u8id = this.syncService.pushU8AccountForEdit(u8Customer, ds_s);
                String u8idAnmai = this.syncService.pushU8AccountForEdit(u8Customer, "3");
                if (u8id == null) {
                    return "源头OA-更新异常：请查看日志";
                }
                log.info("源头OA-更新U8ID：" + u8id);
                //更新账户信息--更新每刻 客户的账号信息（已经添加了的客户）
                Map<String, String> accMap = new HashMap<>();
                if (!NormalUtil.null2String(oaCustomer.getLianhangh()).equals("") || !NormalUtil.null2String(oaCustomer.getZhanghao()).equals("")) {
                    accMap.put("accountType", "BANK");
                    accMap.put("accountName", oaCustomer.getKehumc());
                    accMap.put("accountNumber", NormalUtil.trimString(oaCustomer.getZhanghao()));
                    accMap.put("bankBranchNo", oaCustomer.getLianhangh());
                }
                //取消更新每刻往来
//                pushMaycurPartner(u8Customer, accMap);

            }
            //每刻自定义档案更新(客户),若不存在，会自动新增，无须调用pushCustomReference方法
            editCustomReference(oaToU8.convertFun(oaCustomer, prod));
        } else {
            //钉钉报警
            dingMessageUtil.pushMessage(null, "OAPush：prod操作异常");
            return "OAPush：prod操作异常";
        }
        return null;
    }


    /**
     * 同步oa流程下来的客户同步对象(同时也推送到oa的表单建模中，但如果推送的是重复的，可能会有异常),利用上面的推送方法(only add)
     *
     * @return
     */
    @PostMapping("/wfPushSync")
    @Deprecated
    @ResponseBody
    public String manualSyncPartByOA(@RequestBody Map<String, String> map) {
        //获取到的oarequest
        try {
            log.info("OA流程请求新增requestid:" + map.get("requestid"));
            OACustomer oaCustomer = this.syncService.wfToMode(map.get("requestid"));
            if (oaCustomer != null) {
                oaCustomerPush(oaCustomer, "add");
                log.info("oa流程推送成功：{}", map.get("requestid"));
                return "oa流程转数据推送正常";
            } else {
                //流程转数据时，出现客户或供应商信息重复(1.客户重复新增；2.客户需要更新一些信息;3.先出现客户后加同名供应商或者先出现供应商后出现客户)
                OACustomer oaCustomer1 = this.syncService.wfToMode2(map.get("requestid"));
                //判断U8是否存在
                if (StringUtils.isNotBlank(oaCustomer1.getU8kehubm())) {
                    //判断是否是客户转供应商
                    if (oaCustomer1.getKehulb() == 1 || oaCustomer1.getKehulb() == 10) {
                        this.vendorSyncController.oaVendorPushForAdd(oaCustomer1);
                        log.info("符合条件3.先出现客户后加同名供应商或者先出现供应商后出现客户");
                        return "符合条件3.先出现客户后加同名供应商或者先出现供应商后出现客户";
                    }
                    //直接推送每刻
                    Map<String, String> accMap = new HashMap<>();
                    if (!NormalUtil.null2String(oaCustomer1.getLianhangh()).equals("") || !NormalUtil.null2String(oaCustomer1.getZhanghao()).equals("")) {
                        accMap.put("accountType", "BANK");
                        accMap.put("accountName", oaCustomer1.getKehumc());
                        accMap.put("accountNumber", NormalUtil.trimString(oaCustomer1.getZhanghao()));
                        accMap.put("bankBranchNo", oaCustomer1.getLianhangh());
                    }
                    U8Customer _u8Customer = this.oaToU8.convertFun(oaCustomer1, "edit");
                    //更新每刻往来
                    if (oaCustomer1.getKehulb().equals(11)) {
                        oaCustomer1.setKehulb(1);
                        this.vendorSyncController.oaVendorPushForAdd(oaCustomer1);
//                        pushMaycurPartner(_u8Customer, accMap);
                        return "每刻收款账号更新完成";
                    } else {
                        pushCustomReferenceToMaycur(_u8Customer);
                    }
                    //推送说明
                    Map<String, String> map1 = new HashMap<>();
                    dingMessageUtil.pushMessage(null, "oa流程转数据,oa台账已经存在U8ID，更新oa台账信息成功，推送maycur账号信息成功");
                    return "oa流程转数据,oa台账已经存在，更新oa台账信息成功，推送maycur账号信息成功";
                } else {
                    oaCustomerPush(oaCustomer1, "add");
                    dingMessageUtil.pushMessage(null, "oa流程转数据,oa台账已经不存在U8ID，新增erp，更新oa台账，推送maycur账号信息");
                    return "oa流程转数据,oa台账已经不存在U8ID，新增erp，更新oa台账，推送maycur账号信息";
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "请求异常";
        }
    }

    /**
     * 推送每刻的往来客户私有方法
     * 不做转化类，直接在方法中转化
     * u8客户对象+账号信息
     * @return
     */
//    @Deprecated
//    private void pushMaycurPartner(U8Customer customer, Map<String, String> accMap) {
//        try {
//            String path = customer.getSelf_define3().replace("省", "");
//            path = "集团外单位," + path;
//            MayCurPartner partner = new MayCurPartner();
//            partner.setPartnerType("客户");
//            partner.setPartnerProperty("公司");
//            partner.setName(customer.getName());
//            partner.setBusinessCode(customer.getCode());
//            partner.setParentName(path);
//            //账号信息 不为空
//            if (!accMap.isEmpty()) {
//                List<Map<String, String>> lists = new ArrayList<>();
//                lists.add(accMap);
//                partner.setAccounts(lists);
//            }
//            String result = this.syncService.pushMaycurPartener(partner);
//            Map<String, String> msgMap = new HashMap<>();
//        } catch (Exception exception) {
//            exception.printStackTrace();
//            Map<String, String> msgMap = new HashMap<>();
//        }
//    }

    /**
     * 自定义档案推送(客户)
     *
     * @param customer
     */
    private void pushCustomReferenceToMaycur(U8Customer customer) {
        try {
            Map<String, String> map = new HashMap<>();
            String path = customer.getSelf_define3().replace("省", "").replace("市", "");
            map.put("path", path);
            map.put("id", customer.getCode());
            map.put("name", customer.getName());
            String result = this.syncService.pushMaycurCustomerReference(map);
            dingMessageUtil.pushMessage(null, "客户自定义档案同步--推送每刻结果:" + result);
        } catch (Exception e) {
            dingMessageUtil.pushMessage(null, "客户自定义档案同步--推送每刻异常" + e);
        }
    }

    /**
     * 每刻自定义档案更新(客户)
     * 如果不存在时,直接新增
     *
     * @param customer
     */
    private void editCustomReference(U8Customer customer) {
        try {
            Map<String, String> map = new HashMap<>();
            String path = customer.getSelf_define3().replace("省", "").replace("市", "");
            map.put("path", path);
            map.put("id", customer.getCode());
            map.put("name", customer.getName());
            log.info("推送信息为--->{}", map.toString());
            String result = this.syncService.editMaycurCustomerReference(map);
            dingMessageUtil.pushMessage(null, "客户自定义档案更新--更新每刻结果:" + result);
        } catch (Exception e) {
            dingMessageUtil.pushMessage(null, "客户自定义档案更新--更新每刻异常" + e);
        }
    }

    /**
     * 独立功能接口
     */
    /**
     * 获取ERP中客户ID （通过客户名称查询U8ID）
     */
    @GetMapping("/getCustomerCode")
    public Map<String, String> getERPCustomerCode(@RequestParam(value = "name") String name) {
        Map<String, String> reMap = new HashMap<>();
        reMap.put("code", syncService.checkErpCustomer(name));
        return reMap;
    }

    //-----------------以下为本方法的独立方法

    /**
     * 客户推送到bip中
     *
     * @param crmCustomer
     */
    private void handleBipCustomerFromCrm(CrmCustomer crmCustomer) {
        CustomerForBip bipCustomer = crmToBip.convertFun(crmCustomer);
        //增加bip客户
        String bipPkCode = bipCustomerService.addCustomer(bipCustomer);
        String bipCode = bipCustomerService.getCustomerCode(bipPkCode);
        //分配bip客户 todo:根据组织架构变动时 需要调整
        String[] argOrg = {"BS01", "BS0101", "BS0110", "BS0114", "BS0115"};
        boolean flag = bipCustomerService.assignCustomer(bipCode, argOrg);
        //钉钉提醒
        dingMessageUtil.pushMessage(null, "bip(Customer)推送结果FromCrm==>" + flag);
    }

    private void handleBipCustomerFromOA(OACustomer oaCustomer, String prod) {
        CustomerForBip bipCustomer = oaToBip.convertFun(oaCustomer, prod);
        //增加bip客户
        String bipPkCode = bipCustomerService.addCustomer(bipCustomer);
        String bipCode = bipCustomerService.getCustomerCode(bipPkCode);
        //分配bip客户 todo:根据组织架构变动时 需要调整
        String[] argOrg = {"BS01", "BS0101", "BS0110", "BS0114", "BS0115"};
        boolean flag = bipCustomerService.assignCustomer(bipCode, argOrg);
        //钉钉提醒
        dingMessageUtil.pushMessage(null, "bip推送结果FromOa==>" + flag);
    }



    //----------------------------------以下为手动接口---------------------------------------------------------

    /**
     * 手动同步 part1
     * 更新crm客户档案中，new_erp_num为空的，但是在erp（名称搜索）中存在的客户档案。
     *
     * @return
     */
    @PostMapping("/asSyncPart1")
    @ResponseBody
    public String asSyncPart1() {
        //"http://172.16.0.190:5555/crm/api/data/v8.2/accounts?$select=name,new_erp_num,new_oa_id&$filter=new_erp_num eq null and statecode eq 0"
        String returnStr = this.syncService.asSyncErpnum();
        return "更新crm客户档案中 new_erp_num为空的，但是在erp（名称搜索）中存在的客户档案," + returnStr;
    }

    /**
     * 手动同步 part2
     * 更新crm客户档案中，new_oa_id为空的，但是在oa台账中（名称搜索）中存在的客户档案。
     *
     * @return
     */
    @PostMapping("/asSyncPart2")
    @ResponseBody
    public String asSyncPart2() {
        //"http://172.16.0.190:5555/crm/api/data/v8.2/accounts?$select=name,new_erp_num,new_oa_id&$filter=new_oa_id eq null and statecode eq 0"
        String returnStr = this.syncService.asSyncOaId();
        return "更新crm客户档案中 new_oa_id为空的，但是在oa（名称搜索）中存在的客户档案," + returnStr;
    }

    /**
     * 手动同步crm客户档案
     *
     * @param
     * @return
     */
    @PostMapping("/manualSyncPart1")
    @ResponseBody
    public String manualSyncPart1(@RequestParam(value = "guid") String guid, @RequestParam(value = "prod") String prod) {
        if ("".equals(guid) || !"manual".equals(prod)) {
            return "CRM客户GUID异常";
        }
        String resStr = "";
        //获取crm客户对象
        CrmCustomer crmCustomer = syncService.getCrmAccount(guid);
        String u8id = "";
        //确定new_erp_num 和 new_oaid状态
        if (crmCustomer.getNew_erp_num() == null) {
            //new_erp_num为空
            //搜索U8是否存在这个客户（sql查询）
            Map<String, String> map1 = this.syncService.getErpCus(crmCustomer);
            //erp 不存在这个客户，需要新增
            if ("0".equals(map1.get("state"))) {
                U8Customer u8Customer = crmToU8.convertFun(crmCustomer, "add");
                u8id = this.syncService.pushU8AccountForAdd(u8Customer, ds_s);
                crmCustomer.setNew_erp_num(u8id);
                log.info("需要更新的CRMID:{}", u8id);
                Map<String, Object> reqMap1 = new HashMap<>();
                reqMap1.put("new_erp_num", u8id);
                this.syncService.updateCrmAccount(reqMap1, crmCustomer.getAccountid());
                resStr = resStr + "更新CRM信息成功（插入CRM客户后）\n";
            } else {
                resStr = resStr + map1.get("code") + "\n";
            }
        } else {
            resStr = "crm中已经存在U8ID";
        }

        if (crmCustomer.getNew_oa_id() == null) {
            //new_oa_id 为空
            //搜索oa是否存在这个客户(sql查询)
            Map<String, String> map2 = this.syncService.getOACus(crmCustomer);
            if ("0".equals(map2.get("state"))) {
                //oa 不存在这个客户，需要新增
                OACustomer oaCustomer = crmToOA.convertFun(crmCustomer, "add");
                String oaid = this.syncService.pushOaAccountForAdd(oaCustomer);
                log.info("需要新增的OAID：{}", oaid);
                Map<String, Object> reqMap = new HashMap<>();
                reqMap.put("new_oa_id", oaid);
                this.syncService.updateCrmAccount(reqMap, crmCustomer.getAccountid());
                resStr = resStr + "更新OA信息成功（插入OA客户后）" + "\n";
            } else {
                resStr = resStr + map2.get("code") + "\n";

            }

        }
        return resStr;
    }


}
